<template>
  <ul>
    <li v-for="(item, index) in todoLists" :key="item.id">
      <p>
        {{ index + 1 }}、{{ item.name }}
        <span class="add" @click="add">新增</span>
        <span class="del" @click="del(item.id)" v-if="todoLists.length > 1"
          >删除</span
        >
      </p>
    </li>
  </ul>
</template>
<script lang="ts">
import { reactive } from "vue";

export default {
  setup() {
    const todoLists: { name: string; id: number }[] = reactive([
      {
        id: 1,
        name: "第1件事",
      },
    ]);
    // 新增
    const add = () => {
      const lastId = todoLists[todoLists.length - 1].id;
      const newId = lastId + 1;
      const newName = `第${newId}件事`;

      todoLists.push({
        id: newId,
        name: newName,
      });
    };
    // 删除
    const del = (id: number) => {
      let delIndex;

      todoLists.forEach((item, index) => {
        if (item.id === id) {
          delIndex = index;
        }
      });
      delIndex !== undefined && todoLists.splice(delIndex, 1);
    };

    return {
      todoLists,
      add,
      del,
    };
  },
};
</script>
<style lang="less" scoped>
ul {
  width: 400px;
  margin: 0;
  padding: 0;
  li {
    width: 100%;
    list-style: none;
    text-align: left;
    line-height: 20px;
    span {
      cursor: pointer;
      margin: 0 10px;
      font-size: 12px;
      user-select: none;
    }
  }
}
</style>

